
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const { createProxyMiddleware } = require("http-proxy-middleware");


const server = http.createServer((req, res) => {
    const urlStr = req.url;

    console.log('urlStr', urlStr);

    if (/\/user_api/.test(urlStr)) {
        res.writeHead(200, {
            'content-type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': "*"
        });
        const proxy = createProxyMiddleware('/user_api', {
            target: 'https://api.juejin.cn', // 服务器代理请求地址 https://api.juejin.cn/user_api/v1/author/recommend?aid=2608&uuid=6999458699271521824&category_id=&cursor=0&limit=20
            changeOrigin: true
        });
        proxy(req, res);// 本地请求地址：http://localhost:8080/user_api/v1/author/recommend?aid=2608&uuid=6999458699271521824&category_id=&cursor=0&limit=20
    } else if (/\/api/.test(urlStr)) {
        res.writeHead(200, {
            'content-type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': "*"
        });
        const proxy2 = createProxyMiddleware('/api', {
            target: 'https://www.jianshu.com/', // 服务器代理请求地址 https://www.jianshu.com/users/recommended?seen_ids=&count=5&only_unfollowed=true
            changeOrigin: true,
            pathRewrite: {
                "^/api": "" // 把api替换成空  本地请求地址：http://localhost:8080/api/users/recommended?seen_ids=&count=5&only_unfollowed=true
            }
        });
        proxy2(req, res);
    } else {
        console.log('error');
    }
});

server.listen(8080);

